package com.xz.product.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.product.domain.Product;
import com.xz.product.domain.ProductAttribute;
import com.xz.product.domain.ProductCategoryItem;
import com.xz.product.dto.ProductCategoryDto;
import com.xz.product.dto.ProductCategoryItemDto;
import com.xz.product.dto.ProductCategoryListDto;
import com.xz.product.service.IProductCategoryItemService;
import com.xz.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.product.mapper.ProductCategoryMapper;
import com.xz.product.domain.ProductCategory;
import com.xz.product.service.IProductCategoryService;
import org.springframework.util.CollectionUtils;

/**
 * 商品类别Service业务层处理
 *
 * @author xz
 * @date 2024-01-02
 */
@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements IProductCategoryService {
    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    @Autowired
    private IProductCategoryItemService productCategoryItemService;
    @Autowired
    private IProductService iProductService;

    /**
     * 查询商品类别
     *
     * @param id 商品类别主键
     * @return 商品类别
     */
    @Override
    public ProductCategoryDto selectProductCategoryById(Long id) {
        ProductCategoryDto productCategoryDto = productCategoryMapper.selectProductCategoryById(id);
        if(Objects.nonNull(productCategoryDto)){
            Integer attributeCategory = productCategoryDto.getAttributeCategory();
            List<ProductCategoryItemDto> categoryItemDtoList = this.getProductCategoryItem(id, attributeCategory);
            if(attributeCategory==3){//定制属性
                productCategoryDto.setCustomList(CollectionUtils.isEmpty(categoryItemDtoList) ? new ArrayList<>():categoryItemDtoList);
            }else{
                //非定制属性
                productCategoryDto.setNoCustomList(CollectionUtils.isEmpty(categoryItemDtoList) ? new ArrayList<>():categoryItemDtoList);
                //定制属性
                List<ProductCategoryItemDto> productCategoryItem = this.getProductCategoryItem(id, 3);
                productCategoryDto.setCustomList(CollectionUtils.isEmpty(productCategoryItem) ? new ArrayList<>():productCategoryItem);
            }
        }
        return productCategoryDto;
    }

    /**
     * 查询商品类别列表
     *
     * @param productCategory 商品类别
     * @return 商品类别
     */
    @Override
    public List<ProductCategoryListDto> selectProductCategoryList(ProductCategory productCategory) {
        List<ProductCategoryListDto> productCategoryList = productCategoryMapper.selectProductCategoryList(productCategory);
        if(!CollectionUtils.isEmpty(productCategoryList)){
            productCategoryList.stream().forEach(i->{
                Integer attributeCategory = i.getAttributeCategory();
                List<ProductCategoryItemDto> categoryItemDtoList = this.getProductCategoryItem(i.getId(), attributeCategory);
                if(attributeCategory==3){//定制属性
                    i.setCustomAttribute(categoryItemDtoList.stream().map(j->j.getAttributeName()).collect(Collectors.joining("、")));
                }else{
                    //非定制属性
                    i.setProductAttribute(categoryItemDtoList.stream().map(j->j.getAttributeName()).collect(Collectors.joining("、")));
                    //定制属性
                    List<ProductCategoryItemDto> productCategoryItem = this.getProductCategoryItem(i.getId(), 3);
                    i.setCustomAttribute(productCategoryItem.stream().map(j->j.getAttributeName()).collect(Collectors.joining("、")));
                }
            });
        }
        return productCategoryList;
    }

    /**
     * 新增商品类别
     *
     * @param productCategory 商品类别
     * @return 结果
     */
    @Override
    public AjaxResult insertProductCategory(ProductCategory productCategory) {
        //校验是否已经添加
        int count = this.count(new QueryWrapper<ProductCategory>().eq("product_category", productCategory.getProductCategory()).eq("attribute_category", productCategory.getAttributeCategory()).eq("del_flag", 0));
        if(count>0){
            return AjaxResult.error("数据【"+productCategory.getProductCategory()+"】已存在");
        }
        productCategory.setEncoded(RedisCode.getCode("PC"));
        productCategory.setCreateTime(DateUtils.getNowDate());
        productCategory.setCreateBy(SecurityUtils.getUserId());
        productCategory.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        int insertProductCategory = productCategoryMapper.insertProductCategory(productCategory);
        if(insertProductCategory>0){
            List<ProductCategoryItem> categoryItemList = productCategory.getCategoryItemList();
            categoryItemList.stream().forEach(i->i.setProductCategoryId(productCategory.getId()));
            productCategoryItemService.saveBatch(productCategory.getCategoryItemList());
        }
        return insertProductCategory>0? AjaxResult.success("新增成功"):AjaxResult.error("新增失败");
    }

    @Override
    public AjaxResult setWarnDays(ProductCategory productCategory){
        List<Long> idList = productCategory.getIdList();
        if(CollectionUtils.isEmpty(idList)){
            return AjaxResult.error("请选择需要设置的类别");
        }
        baseMapper.setWarningDays(productCategory);
        return AjaxResult.success("操作成功！");
    }

    /**
     * 修改商品类别
     *
     * @param productCategory 商品类别
     * @return 结果
     */
    @Override
    public AjaxResult updateProductCategory(ProductCategory productCategory) {
        if(productCategory.getId()==null){
            return AjaxResult.error("参数id不能为空");
        }
        //校验是否已经添加
        int count = this.count(new QueryWrapper<ProductCategory>().eq("product_category", productCategory.getProductCategory()).eq("attribute_category", productCategory.getAttributeCategory()).eq("del_flag", 0).ne("id",productCategory.getId()));
        if(count>0){
            return AjaxResult.error("数据【"+productCategory.getProductCategory()+"】已存在");
        }
        productCategory.setUpdateTime(DateUtils.getNowDate());
        productCategory.setUpdateBy(SecurityUtils.getUserId());
        int updateProductCategory = productCategoryMapper.updateProductCategory(productCategory);
        if(updateProductCategory>0){
            //删除分类关联属性配置
            productCategoryItemService.deleteProductCategoryItemById(productCategory.getId());
            List<ProductCategoryItem> categoryItemList = productCategory.getCategoryItemList();
            categoryItemList.stream().forEach(i->i.setProductCategoryId(productCategory.getId()));
            productCategoryItemService.saveBatch(productCategory.getCategoryItemList());
        }
        return updateProductCategory>0? AjaxResult.success("修改成功"):AjaxResult.error("修改失败");
    }

    /**
     * 批量删除商品类别
     *
     * @param ids 需要删除的商品类别主键
     * @return 结果
     */
    @Override
    public int deleteProductCategoryByIds(Long[] ids) {
        return productCategoryMapper.deleteProductCategoryByIds(ids);
    }

    /**
     * 删除商品类别信息
     *
     * @param id 商品类别主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteProductCategoryById(Long id) {
        int count = iProductService.count(new QueryWrapper<Product>().eq("category_id", id).eq("del_flag", 0));
        if(count>0){
            return  AjaxResult.error("当前类别已绑定商品，不能进行删除");
        }
        int deleteProductCategoryById = productCategoryMapper.deleteProductCategoryById(id);
        if(deleteProductCategoryById>0){
            //删除绑定属性参数
            productCategoryItemService.deleteProductCategoryItemById(id);
        }
        return AjaxResult.success("删除成功");
    }

    @Override
    public List<ProductCategoryItemDto> getProductCategoryItem(Long productCategoryId, Integer attributeCategory) {
        return baseMapper.getProductCategoryItem(productCategoryId,attributeCategory);
    }

    @Override
    public Long getId(String productCategory) {
        return baseMapper.getId(productCategory);
    }
}
